import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/config/app_data_config.dart';
import 'package:app/src/ui/app_ui.dart';
import 'package:app/src/http/bean/user.dart';
import 'package:app/src/http/model/user_model.dart';
import 'package:app/src/manager/user_manager.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/ui/route/helper/route_helper.dart';
import 'package:app/src/ui/route/works/public/items/ui_base.dart';
import 'package:app/src/utils/image_path_utils.dart';

import '../main/user/user.dart';

///密码修改
class PassWordRoute extends StatefulWidget {
  @override
  _PassWordState createState() => _PassWordState();
  static bool isShow = false;
}

class _PassWordState extends State<PassWordRoute> {
  _PassWordPresenter presenter = _PassWordPresenter();

  @override
  void initState() {
    super.initState();
    PassWordRoute.isShow = true;
    //获取用户信息
    UserPresenter?.getpersoninfo(context, (value) {
      setState(() {});
    }, isEnableLoad: false, isAuto: false, isAutoLogin: false);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    PassWordRoute.isShow = false;
  }

  @override
  Widget build(BuildContext context) {
    px.init(context);
    marginTop = px.y(180);
    var isV = AppDataConfig.isValidationWithPassword();
    var scaffold = Scaffold(
      backgroundColor: AppColors.backgroundColorWithWhite,
      appBar: AppBar(
        backgroundColor: AppColors.backgroundColorWithWhite,
        elevation: 0,
        leading: AppUi.getBack(context, () {
          if (AppDataConfig.isValidationWithPassword()) {
            var content = AppStrings.of(context).passwords003; //密码修改未完成，是否确认退出？
            AppDialog.showDialogWithAlert(context, content: content)
                ?.then((value) {
              if (value ?? false) {
                //确认退出
                AppRouteHelper.exit();
              }
            });
            return true;
          }
          return false;
        }, isCha: isV),
      ),
      body: Material(
          color: AppColors.backgroundColorWithWhite, child: _body(context)),
    );
    return WillPopScope(
      child: scaffold,
      onWillPop: () async {
        if (AppDataConfig.isValidationWithPassword()) {
          var content = AppStrings.of(context).passwords003; //密码修改未完成，是否确认退出？
          AppDialog.showDialogWithAlert(context, content: content)
              ?.then((value) {
            if (value ?? false) {
              //确认退出
              AppRouteHelper.exit();
            }
          });
          return false;
        }
        return true;
      },
    );
  }

  var marginTop = 0.0;

  Widget _body(BuildContext context) {
    return Scrollbar(
      child: SingleChildScrollView(
        physics: BouncingScrollPhysics(),
        child: Form(
            key: _formKey,
            child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.only(top: px.y(100)),
                  child: Align(
                    child: Hero(
                      tag: AppUi.hero_tag_launch,
                      child: Image.asset(
                        ImagePathUtils.getPathWithImage("ic_logo_blue.png"),
                        width: px.dp(331),
                        height: px.dp(203),
                      ),
                    ),
                    alignment: Alignment.topCenter,
                  ),
                ),
                Builder(builder: (context) {
                  if (AppDataConfig.isValidationWithPassword()) {
                    var text = Text(
                      AppStrings.of(context).passwords001,
                      style: TextStyle(color: Colors.redAccent, fontSize: 18),
                    );
                    return Container(
                      child: text,
                      alignment: Alignment.topLeft,
                      margin: AppEdgeInsets.marginWithItem(top: marginTop),
                    );
                  }
                  return AppUi.getEmptyView();
                }),
                //原始密码
                Center(
                  child: Container(
                    margin: AppEdgeInsets.marginWithItem(top: marginTop),
                    child: _oldPassword(),
                  ),
                ),
                //新密码
                Center(
                  child: Container(
                    margin: AppEdgeInsets.marginWithItem(top: marginTop),
                    child: _newPassword(),
                  ),
                ),
                //确认密码
                Center(
                  child: Container(
                    margin: AppEdgeInsets.marginWithItem(top: marginTop),
                    child: _confirmpassWord(),
                  ),
                ),
                //密码修改
                Center(
                  child: Container(
                    margin: AppEdgeInsets.marginWithItem(top: marginTop),
                    child: MaterialButton(
                      height: 55,
                      minWidth: px.screenWidth(),
                      onPressed: () {
                        //print('点击事件${presenter.toString()}');
                        var b = _formKey.currentState?.validate() ?? false;
                        if (b) {
                          //fixme 必须添加点击事件，不然背景色color不起作用。
                          presenter?.passwordUpdate(context);
                        }
                      },
                      //label 右边控件（一般为文本），不能为空
                      color: AppColors.themeColorWithServerAdress,
                      //color 按钮颜色
                      splashColor: Colors.black12,
                      //splashColor 点击时，飞溅扩散的颜色
                      //highlightColor: Colors.red, //highlightColor 点击时按钮颜色
                      colorBrightness: Brightness.light,
                      //colorBrightness 按钮亮度；Brightness.dark 暗系风格;Brightness.light 高亮(默认)
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.all(Radius.circular(60))),
                      //shape 形状
                      textColor: Colors.white,
                      //文本默认颜色
                      child: Text(
                        AppStrings.of(context).passwordUpdate,
                        style: AppStyle.textStyleWithButton(),
                      ), //fixme 子控件
                    ),
                  ),
                )
              ],
            )),
      ),
    );
  }

  GlobalKey<FormState> _formKey = GlobalKey();

  //原始密码
  TextEditingController? _oldPassWordTextEditingController;

  Widget _oldPassword() {
    if (_oldPassWordTextEditingController == null) {
      _oldPassWordTextEditingController = TextEditingController();
    }
    return StatefulBuilder(
      builder: (context, setState) {
        return TextFormField(
          cursorColor: AppColors.themeColorWithServerAdress,
          //鼠标颜色
          controller: _oldPassWordTextEditingController,
          onChanged: (value) {
            //文本发生变化
            setState(() {
              presenter?.oldPassWord = value;
            });
          },
          decoration: InputDecoration(
            hintText: AppStrings.of(context).oldPassword, //默认文本
            focusedBorder: UnderlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(0)),
                borderSide: BorderSide(
                    color: AppColors.themeColorWithServerAdress, width: 1)),
            prefixIcon: Container(
              child: Center(
                child: Image.asset(
                  ImagePathUtils.getPathWithImage("ic_password.png"),
                  width: 22,
                ),
              ),
              width: 60,
            ),
            //尾部删除图标
            suffixIcon:
                (isDataMoreLength(_oldPassWordTextEditingController?.text))
                    ? Container(
                        width: 40,
                        height: 40,
                        child: InkWell(
                          child: Center(
                            child: Icon(
                              Icons.clear,
                              color: Colors.grey,
                              size: 16,
                            ),
                          ),
                          onTap: () {
                            //文本清除
                            setState(() {
                              presenter?.oldPassWord = "";
                              _newPassWordTextEditingController?.text = "";
                            });
                          },
                        ),
                      )
                    : null,
          ),
          validator: (value) {
            if (StringUtils.isEmpty(value)) {
              return AppStrings.of(context).oldPasswordNotEmpty;
            }
            return null; //fixme 成功直接返回空null;空字符串''也不行，必须是空null
          },
          obscureText: true,
        );
      },
    );
  }

  //新密码
  TextEditingController? _newPassWordTextEditingController;

  Widget _newPassword() {
    if (_newPassWordTextEditingController == null) {
      _newPassWordTextEditingController = TextEditingController();
    }
    return StatefulBuilder(
      builder: (context, setState) {
        return TextFormField(
          cursorColor: AppColors.themeColorWithServerAdress,
          //鼠标颜色
          controller: _newPassWordTextEditingController,
          //文本控制器
          onChanged: (value) {
            //文本发生变化
            setState(() {
              presenter?.newPassWord = value;
            });
          },
          decoration: InputDecoration(
            hintText: AppStrings.of(context).newPassword, //默认文本
            focusedBorder: UnderlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(0)),
                borderSide: BorderSide(
                    color: AppColors.themeColorWithServerAdress, width: 1)),
            prefixIcon: Container(
              child: Center(
                child: Image.asset(
                  ImagePathUtils.getPathWithImage("ic_password.png"),
                  width: 22,
                ),
              ),
              width: 60,
            ),
            //尾部删除图标
            suffixIcon:
                (isDataMoreLength(_newPassWordTextEditingController?.text))
                    ? Container(
                        width: 40,
                        height: 40,
                        child: InkWell(
                          child: Center(
                            child: Icon(
                              Icons.clear,
                              color: Colors.grey,
                              size: 16,
                            ),
                          ),
                          onTap: () {
                            //文本清除
                            setState(() {
                              presenter?.newPassWord = "";
                              _newPassWordTextEditingController?.text = "";
                            });
                          },
                        ),
                      )
                    : null,
          ),
          validator: (value) {
            if (StringUtils.isEmpty(value)) {
              return AppStrings.of(context).newPasswordNotEmpty;
            }
            return null; //fixme 成功直接返回空null;空字符串''也不行，必须是空null
          },
          obscureText: true,
        );
      },
    );
  }

  //确认密码
  TextEditingController? _passWordTextEditingController;

  Widget _confirmpassWord() {
    if (_passWordTextEditingController == null) {
      _passWordTextEditingController =
          TextEditingController(text: presenter?.passWord);
    }
    return StatefulBuilder(
      builder: (context, setState) {
        return TextFormField(
          cursorColor: AppColors.themeColorWithServerAdress,
          //鼠标颜色
          controller: _passWordTextEditingController,
          //文本控制器
          onChanged: (value) {
            //文本发生变化
            setState(() {
              presenter?.passWord = value;
            });
          },
          decoration: InputDecoration(
            hintText: AppStrings.of(context).confirmPassword, //默认文本
            focusedBorder: UnderlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(0)),
                borderSide: BorderSide(
                    color: AppColors.themeColorWithServerAdress, width: 1)),
            prefixIcon: Container(
              child: Center(
                child: Image.asset(
                  ImagePathUtils.getPathWithImage("ic_password.png"),
                  width: 22,
                ),
              ),
              width: 60,
            ),
            //尾部删除图标
            suffixIcon: (isDataMoreLength(_passWordTextEditingController?.text))
                ? Container(
                    width: 40,
                    height: 40,
                    child: InkWell(
                      child: Center(
                        child: Icon(
                          Icons.clear,
                          color: Colors.grey,
                          size: 16,
                        ),
                      ),
                      onTap: () {
                        //文本清除
                        setState(() {
                          presenter?.passWord = "";
                          _passWordTextEditingController?.text = "";
                        });
                      },
                    ),
                  )
                : null,
          ),
          validator: (value) {
            if (StringUtils.isEmpty(value)) {
              return AppStrings.of(context).confirmPasswordNotEmpty;
            } else if (value != presenter?.newPassWord) {
              return AppStrings.of(context).confirmPasswordNotSame;
            }
            if (AppDataConfig.isValidationWithPassword2()) {
              var PersonCode = UserManager.getUserInfo()?.PersonCode;
              if (value == PersonCode) {
                return AppStrings.of(context).passwords002; //密码与账号不能一样
              }
            }
            return null; //fixme 成功直接返回空null;空字符串''也不行，必须是空null
          },
          obscureText: true,
        );
      },
    );
  }
}

class _PassWordPresenter {
  //原始密码
  String? oldPassWord = null;

  //新密码
  var newPassWord = "";

  //确认密码
  var passWord = "";

  _PassWordPresenter() {}

  UserPassData? userPassData;

  ///密码修改
  void passwordUpdate(BuildContext context) {
    if (userPassData == null) {
      userPassData = UserPassData();
    }
    userPassData?.FactoryId = AppDataConfig.getFactory()?.FactoryId;
    userPassData?.UserName = UserManager.getUserInfo()?.PersonCode;
    userPassData?.PassWord = oldPassWord;
    userPassData?.NewPassWord = newPassWord;
    UserModel.changepassword(context, true, userPassData, (value) {
      if (value.isSuccessForCode()) {
        //密码修改成功
        UserManager.passwordUpdate(context);
      } else {
        AppDialog.showDialogWithInfo(context, content: value?.MsgDetail);
      }
    });
  }
}
